<template>
  <div>
    <!--面包屑-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :class="['btnBar']">
        <el-button type="primary" @click="handleExpandOrCollapse">{{defaultExpandAll?'收起分类':'展开分类'}}
        </el-button>
        <el-input :class="['searchInput']" placeholder="搜索分类"
                  v-model="cateSearchText" @input="handleCateSearchTextInput" class="input-with-select">
        </el-input>

        <el-button type="primary" @click="handleAddCateButtonClick()">添加一级分类</el-button>
      </el-row>
      <el-row>
        <el-card :class="['cateTree']" shadow="never">

          <el-row>
            <el-col :span="18" :class="['tableArea']">
              <el-row :class="['titleBar']">
                <h1 :class="['tableTitle']">商品分类表</h1>
              </el-row>
              <el-row>
                <el-table

                  highlight-current-row
                  ref="cateTableRef"
                  :data="tableData"
                  style="width: 100%"
                  row-key="id"
                  :default-expand-all="defaultExpandAll"
                  :indent="40"
                  :row-class-name="rowClassName"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                >

                  <el-table-column
                    label="分类名称"
                    width="400"
                  >
                    <template slot-scope="scope">
                      <span :class="['cateName']">
                        <input :class="{'cateInput':true}"
                               @change="handleCateNameBlur(scope.row)"
                               v-model="scope.row.name"></input>
                      </span>

                    </template>
                  </el-table-column>

                  <el-table-column
                    label="显示"
                    width="80"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <el-switch @change="handleIsShowChange(scope.row)"
                                 :active-value="1"
                                 :inactive-value="0"
                                 v-model="scope.row.isShow"></el-switch>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="备注">
                    <template slot-scope="scope">
                      <el-input style="width: 100%" :class="{'cateInput':true}"
                                @change="handleCateRemarksBlur(scope.row)"
                                v-model="scope.row.remarks"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    width="100"
                  >
                    <template slot-scope="scope">

                      <el-tooltip effect="light" content="删除分类" placement="top-end">
                        <el-button type="danger"
                                   @click="handleDeleteCateButtonClick(scope.row)"
                        >删除
                        </el-button>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="添加"
                    width="100">
                    <template slot-scope="scope">
                      <el-tooltip v-if="!scope.row.isLeaf" effect="light" content="添加子级分类" placement="top-end">
                        <el-button
                          @click="handleAddCateButtonClick(scope.row)"
                          type="primary">添加
                        </el-button>
                      </el-tooltip>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="详情"
                    width="100">
                    <template slot-scope="scope">
                      <el-tooltip v-if="scope.row.isLeaf" effect="light" content="分类的属性与规格详情" placement="top-end">
                        <el-button
                          @click="handleCateDetailsButtonClick(scope.row)"
                          type="primary">详情
                        </el-button>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
            </el-col>


          </el-row>
        </el-card>
      </el-row>


    </el-card>
    <!--属性与规格对话框-->
    <el-dialog
      :center="true"
      :visible.sync="isCateDetailsVisible" width="50%">
      <el-row :class="['detailArea']">
        <el-form :inline="true">
          <el-row style="font-size: 18px;">
            <el-col :span="10">
              <span>分类名称: </span><span
              style="border-bottom:1px solid #b4bccc;padding:5px;color:black;font-weight: bold;">{{currentRow.name}}</span>
            </el-col>
            <el-col :span="7">
              <span>显示: </span><span><el-switch :active-value="1" :inactive-value="0" v-model="currentRow.isShow"
                                                disabled></el-switch></span>
            </el-col>
          </el-row>

        </el-form>
      </el-row>

      <el-row :class="['attrsAndSpecsCollapse']"
      >
        <el-collapse
          style="border-radius: 5px;"
          v-model="attrsAndSpecsCollapseActiveName">
          <el-collapse-item name="1">
            <template slot="title">
              <div style="width: 100%;">
                <span :class="['collapseTitle']">属性列表</span>
                <el-popover
                  placement="top-start"
                  title="新属性名称:"
                  width="200"
                  trigger="hover"
                  style="font-size: 20px;float: right"
                >
                  <el-input placeholder="请输入新属性" v-model="newAttr">
                    <template slot="append">
                      <el-button icon="el-icon-check" @click="handleAddAttrButtonClick"></el-button>
                    </template>
                  </el-input>
                  <el-button style="font-size: 30px;border:none;background-color:rgba(0,0,0,0);" type="primary" plain
                             slot="reference">
                    <i class="el-icon-circle-plus"></i>
                  </el-button>
                </el-popover>
              </div>
            </template>
            <el-row>
              <el-tag closable size="medium"
                      @close="handleAttrTagClose(attr.id)"
                      v-for="attr of currentRow.attrs" :key="'attr'+attr.id">
                {{attr.name}}
              </el-tag>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template slot="title">
              <div style="width: 100%;">
                <span :class="['collapseTitle']">规格列表</span>
                <el-popover
                  placement="top-start"
                  title="新规格名称:"
                  width="200"
                  trigger="hover"
                  style="font-size: 20px;float: right"
                >
                  <el-input placeholder="请输入新规格" v-model="newSpec">
                    <template slot="append">
                      <el-button icon="el-icon-check" @click="handleAddSpecButtonClick"></el-button>
                    </template>
                  </el-input>
                  <el-button style="font-size: 30px;border:none;background-color:rgba(0,0,0,0);" type="primary" plain
                             slot="reference">
                    <i class="el-icon-circle-plus"></i>
                  </el-button>
                </el-popover>
              </div>

            </template>
            <el-row>
              <el-tag closable size="medium"
                      @close="handleSpecTagClose(spec.id)"
                      v-for="spec of currentRow.specs" :key="'spec'+spec.id">

                {{spec.name}}
              </el-tag>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="3">
            <template slot="title">
              <div style="width: 100%;">
                <span :class="['collapseTitle']">品牌列表</span>
              </div>

            </template>
            <el-row>
              <el-tag size="medium"
                      v-for="brand of currentRow.brands" :key="'brand'+brand.id">

                {{brand.name}}
              </el-tag>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-row>
      <template slot="title">
        <h1 style="font-size: 30px;">属性与规格</h1>
      </template>
    </el-dialog>


    <!--添加分类对话框-->
    <el-dialog title="添加分类"
               :center="true"
               :visible.sync="isAddCateDialogVisible" width="50%">
      <span v-if="addCateData.pid==0" style="color: red">* 添加顶级分类</span>
      <el-form>
        <el-form-item label="父分类:" v-if="addCateData.pid!=0">
          <el-input v-model="addCateData.parentName"></el-input>
        </el-form-item>

        <el-form-item label="分类名称:">
          <el-input v-model="addCateData.name"></el-input>
        </el-form-item>
        <el-form-item label="显示:">
          <el-switch :active-value="1" :inactive-value="0" v-model="addCateData.isShow"></el-switch>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="addCateData.remarks"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelAddCateButtonClick()">取 消</el-button>
        <el-button type="primary" @click="handleConfirmAddCateButtonClick()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  import {readyAllCatesFunction} from "../../funcs/commons";
  import Vue from 'vue'

  export default {
    name: "ProdCate",
    data() {
      return {
        //树型表格字段映射
        props: {
          label: 'name',
          children: 'children',
          isLeaf: 'isLeaf'
        },
        //默认展示变量
        defaultExpandAll: false,
        // 搜索文件数据源
        cateSearchText: '',
        // 当前操作行
        currentRow: {
          name: '',
          parentName: '',
          isShow: 1,
          attrs: [],
          specs: []
        },
        // 折叠面板的展开列表
        attrsAndSpecsCollapseActiveName: ['1', '2', '3'],
        //添加新属性时数据绑定
        newAttr: '',
        //添加新规格时数据绑定
        newSpec: '',
        // 当前分类
        currentCate: {
          id: 0,
          name: '',
          isShow: 1,
          isFloor: false,
          pid: 0,
          pCate: ''
        },
        //
        setFloorCateDialogVisible: false,

        tableData: [],

        addCateData: {
          name: '',
          parentName: '',
          isShow: 1,
          remarks: '',
          pid: 0
        },
        isAddCateDialogVisible: false,
        isCateDetailsVisible: false,
        cateTableData: []
      }

    },

    created() {
      this.getCategoriesFunction();
    },


    methods: {
      //获取分类数据
      getCategoriesFunction() {
        this.api.__api__Categories().then(data => {
          this.cateTableData = data.data.map(v => this.recursionMapCateDatasFunction(v));
          Vue.set(this, 'tableData', this.cateTableData);
        })
      }
      ,
      //添加规格
      handleAddSpecButtonClick() {
        if (this.newSpec) {
          this.api.__api__CategoriesSpecsAdd(this.currentRow.id, this.newSpec)
            .then(data => {
              this.newSpec = '';
              this.api.__api__CategoriesSpecs(this.currentRow.id)
                .then(data1 => {
                  Vue.set(this, 'currentRow', Object.assign({}, this.currentRow, {specs: data1.data}));
                })
              this.$message.success(data.message);
            }).catch(error => {
            console.log(error)
          });
        } else {
          this.$message.info("新的规格不能为空")
        }
      },
      //添加属性
      handleAddAttrButtonClick() {
        if (this.newAttr) {
          this.api.__api__CategoriesAttrsAdd(this.currentRow.id, this.newAttr)
            .then(data => {
              this.newAttr = '';
              this.api.__api__CategoriesAttrs(this.currentRow.id)
                .then(data1 => {
                  Vue.set(this, 'currentRow', Object.assign({}, this.currentRow, {attrs: data1.data}))
                })
              this.$message.success(data.message);
            }).catch(error => {
            console.log(error)
          });
        } else {
          this.$message.info("新的属性不能为空")
        }
      },

      //取消添加分类
      handleCancelAddCateButtonClick() {
        this.addCateData = {};
        this.isAddCateDialogVisible = false;
      },

      //确认添加分类
      handleConfirmAddCateButtonClick() {
        console.log("data:" + JSON.stringify(this.addCateData))
        this.api.__api__CategoriesAdd(this.addCateData)
          .then(data => {
            this.isAddCateDialogVisible = false;
            this.getCategoriesFunction();
            this.$message.success(data.message);
          }).catch(error => {
          this.$message.error(error);
        })

      },
      //删除分类
      async handleDeleteCateButtonClick(row) {
        const result = await this.$confirm("确定要删除[" + row.name + "]分类?", "提示");
        if (result === 'confirm') {
          this.api.__api__CategoriesDelete(row.id)
            .then(data => {
              readyAllCatesFunction();
              this.$message.success(data.message);
            }).catch(error => {
            //this.$message.error(error);
          })
        }
      },
      //分类详情
      handleCateDetailsButtonClick(row) {
        if (!row.children) {
          this.refreshCurrentRow(row);
          this.isCateDetailsVisible = true;
        } else {
          this.currentRow = JSON.parse(JSON.stringify(row));
          this.isCateDetailsVisible = true;
        }
      },

      // 刷新获取分类的属性，规格和品牌列表
      refreshCurrentRow(row) {
        this.currentRow = JSON.parse(JSON.stringify(row));
        this.api.__api__CategoriesAttrs(row.id).then(data => {
          Vue.set(this, 'currentRow', Object.assign({}, this.currentRow, {attrs: data.data}));
          this.api.__api__CategoriesSpecs(row.id).then( data1 => {
            Vue.set(this, 'currentRow', Object.assign({}, this.currentRow, {specs: data1.data}));
            this.api.__api__BrandsOfCategory(row.id)
              .then(data2 => {
                Vue.set(this, 'currentRow', Object.assign({}, this.currentRow, {brands: data2.data}));
              })
              .catch(error => null);
          }).catch(error=>{
            this.api.__api__BrandsOfCategory(row.id)
              .then(data2 => {
                Vue.set(this, 'currentRow', Object.assign({}, this.currentRow, {brands: data2.data}));
              })
              .catch(error => null);
          });
        }).catch(error =>{
          this.api.__api__CategoriesSpecs(row.id).then( data1 => {
            Vue.set(this, 'currentRow', Object.assign({}, this.currentRow, {specs: data1.data}));
            this.api.__api__BrandsOfCategory(row.id)
              .then(data2 => {
                Vue.set(this, 'currentRow', Object.assign({}, this.currentRow, {brands: data2.data}));
              })
              .catch(error => null);
          }).catch(error=>{
            this.api.__api__BrandsOfCategory(row.id)
              .then(data2 => {
                Vue.set(this, 'currentRow', Object.assign({}, this.currentRow, {brands: data2.data}));
              })
              .catch(error => null);
          });
        });

      },

      // 分类搜索回调
      handleCateSearchTextInput() {
        if (this.cateSearchText && this.cateSearchText.length > 0 && this.cateTableData) {
          var tb = JSON.parse(JSON.stringify(this.cateTableData));
          Vue.set(this, 'tableData', this.recursionSearchDataFunction(tb, this.cateSearchText));
          this.defaultExpandAll = true;
          this.handleExpandAll();
        } else {
          Vue.set(this, 'tableData', this.cateTableData);
          this.defaultExpandAll = false;
          this.handleCollapseAll();

        }
      },

      // 添加分类
      handleAddCateButtonClick(row) {
        if (row) {
          this.addCateData.pid = row.id;
          this.addCateData.parentName = row.name;
          this.addCateData.isShow = row.isShow;
          if (row.pid == 0) {
            this.addCateData.isFloor = 1;
          } else {
            this.addCateData.isFloor = 0;
          }
        } else {
          this.addCateData.pid = 0;
          this.addCateData.isFloor = 1;
          this.addCateData.isShow = true;
        }

        this.isAddCateDialogVisible = true;
      },

      // 修改分类备注
      async handleCateRemarksBlur(row) {
        const result = await this.$confirm("确定要修改分类备注?", "提示");
        if (result === 'confirm') {
          this.api.__api__CategoriesRemarksUpdate(row.id, row.remarks)
            .then(data => {
              this.getCategoriesFunction();
              this.$message.success(data.message);
            }).catch(error => {
            this.$message.error(error);
          })
        }
      },

      // 修改分类名称
      async handleCateNameBlur(row) {
        const result = await this.$confirm("确定要修改分类名称?", "提示");
        if (result === 'confirm') {
          this.api.__api__CategoriesNameUpdate(row.id, row.name)
            .then(data => {
              this.getCategoriesFunction();
              this.$message.success(data.message);
            }).catch(error => {
            this.$message.error(error);
          })
        }
        console.log("blur...... id=" + id);
      },

      // 修改分类显示状态
      handleIsShowChange(row) {
        this.api.__api__CategoriesShowUpdate(row.id, row.isShow)
          .then(data => {
            this.getCategoriesFunction();
            this.$message.success(data.message);
          }).catch(error => {
          this.$message.error(error);
          row.isShow = Math.abs(1 - row.isShow);
        })
      },

      // 删除分类的一个规格
      async handleSpecTagClose(specId) {
        const result = await this.$confirm("确定要删除此规格?", "提示");
        if (result === 'confirm') {
          this.api.__api__CategoriesSpecsDelete(specId)
            .then(data => {
              this.api.__api__CategoriesSpecs(this.currentRow.id)
                .then(data1 => {
                  Vue.set(this, 'currentRow', Object.assign({}, this.currentRow, {specs: data1.data}));
                }).catch(error => null);
              this.$message.success(data.message);
            }).catch(error => {
            this.$message.error(error);
          });
        }
      },

      // 删除分类的一个属性
      async handleAttrTagClose(attrId) {
        const result = await this.$confirm("确定要删除此属性?", "提示");
        if (result === 'confirm') {
          this.api.__api__CategoriesAttrsDelete(attrId)
            .then(data => {
              this.api.__api__CategoriesAttrs(this.currentRow.id)
                .then(data1 => {
                  Vue.set(this, 'currentRow', Object.assign({}, this.currentRow, {attrs: data1.data}));
                }).catch(error => null);
              this.$message.success(data.message);
            }).catch(error => {
            this.$message.error(error);
          });
        }
      },

      //递归方法,处理树型表格的展开与折叠
      forArr(arr, isExpand) {
        arr.forEach(i => {
          this.$refs.cateTableRef.toggleRowExpansion(i, isExpand)
          if (i.children) {
            this.forArr(i.children, isExpand)
          }
        })
      },

      //展开或折叠
      handleExpandOrCollapse() {
        if (this.defaultExpandAll) {
          this.handleCollapseAll();
        } else {
          this.handleExpandAll();
        }
        this.defaultExpandAll = !this.defaultExpandAll;
      },

      //展开
      handleExpandAll() {
        this.forArr(this.tableData, true)
      },

      //折叠
      handleCollapseAll() {
        this.forArr(this.tableData, false)
      },

      //树形表格的递归搜索
      recursionSearchDataFunction(array, searchText) {
        var newArray = array.filter(data => {
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          // 注意： some() 不会对空数组进行检测。
          // 注意： some() 不会改变原始数组。
          var ok = Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
            return String(data[key]).toLowerCase().indexOf(searchText) > -1
          });

          if (data.children) {
            var children = this.recursionSearchDataFunction(data.children, searchText);
            if (children.length > 0) {
              data.children = children;
              var childrenOk = true;
            }
          }

          return ok || childrenOk;
        })
        return newArray;
      },

      // 递归修改数据,为了适配树形表格
      recursionMapCateDatasFunction(cate) {

        //这里有个bug,是叶子就没有孩子,它这里必须是叶子等于有孩子，否则第二层数据就不再显示了
        //正常逻辑应该时:  cate.hasChildren = !cate.isLeaf
        //但只有下边这行才正确
        cate.hasChildren = cate.isLeaf;
        if (cate.children !== null && cate.children.length) {
          var children = [];
          for (let child of cate.children) {

            children.push(this.recursionMapCateDatasFunction(child))
          }
          cate.children = children;
        }
        return cate;
      },

      //表格的行点击回调样式，
      rowClassName({row, rowIndex}) {
        if (row.pid == 0) {
          return 'cateTableTreeLevel1';
        } else if (row.hasChildren) {
          return 'cateTableTreeLevel2';
        } else {
          return 'cateTableTreeLevel3';
        }
      }

    }


  }
</script>

<style scoped>
  .btnBar {

    padding: 10px;
  }

  .modifyCard {
    margin: 40px;
    border: 0px solid #eeeeee;
    background-color: rgb(236, 236, 236);

  }

  .titleBar {
    text-align: center;

    margin-bottom: 10px;
  }

  .cateTree {
    margin: 10px;
    border: 1px solid #eeeeee;
  }

  .cateName {
    width: 100%;
    height: 100%;
  }

  .searchInput {
    width: 300px;
  }

  .addBtn {
    float: right;
    font-size: 12px;
    color: #409EFF;
    border: 1px solid #409EFF;
    padding: 3px;
    border-radius: 3px;
  }

  .tableTitle {
    font-size: 24px;
  }

  .tableArea {
    background-color: #ececec;
    border-radius: 5px;
    border: 1px solid #ececec;
  }

  .el-table {
    opacity: 0.8;

  }

  .detailArea {
    background-color: white;
    margin-left: 10px;
    padding: 10px;
    margin-top: -50px;
    border-bottom: 1px solid #b4bccc;
    margin-bottom: 50px;
  }

  .el-tag {
    margin-left: 10px;
    margin-top: 10px;
  }

  .attrsAndSpecsCollapse {
    padding: 0px;
    border-radius: 3px;

  }

  .collapseTitle {
    padding-left: 5px;
    font-size: 18px;
  }

  .cateInput {
    /*width: 100%;*/
    border: 0px solid black;
    /*outline:none;*/
    font-size: 20px;
    padding: 3px;
    padding-top: 10px;
    padding-bottom: 10px;
  }

  .detailInput {
    margin: 10px;
    font-size: 0px;


  }

  .detailInput > * {
    height: 100%;
  }


</style>
